<template>
  <div>
    <div class="box">
      <el-form ref="newsForm" :model="newsForm" :rules="rules">
        <el-form-item
          label="文章标题"
          prop="title"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.title"></el-input>
        </el-form-item>
        <el-form-item
          label="所属栏目"
          prop="typeName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.typeName" disabled></el-input>
        </el-form-item>
        <el-form-item
          label="SEO关键字"
          prop="keywords"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.keywords"></el-input>
        </el-form-item>
        <el-form-item
          label="SEO描述"
          prop="description"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.description"></el-input>
        </el-form-item>
        <el-form-item
          label="文章作者"
          prop="authorName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.authorName"></el-input>
        </el-form-item>
        <el-form-item
          label="文章编辑"
          prop="editorName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.editorName"></el-input>
        </el-form-item>
        <el-form-item
          label="文章简介"
          prop="brief"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="newsForm.brief"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="请输入文章简介"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="是否置顶"
          prop="topRank"
          :label-width="formLabelWidth"
        >
          <el-switch
            v-model="newsForm.topRank"
            active-color="#13ce66"
            inactive-color="#cccccc"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item
          label="是否推荐"
          prop="classicRank"
          :label-width="formLabelWidth"
        >
          <el-switch
            v-model="newsForm.classicRank"
            active-color="#13ce66"
            inactive-color="#cccccc"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item
          label="是否轮播"
          prop="rotateRank"
          :label-width="formLabelWidth"
        >
          <el-switch
            v-model="newsForm.rotateRank"
            active-color="#13ce66"
            inactive-color="#cccccc"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item
          label="显示排序"
          prop="sortRank"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.sortRank"></el-input>
        </el-form-item>
        <el-form-item
          label="浏览量"
          prop="views"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.views"></el-input>
        </el-form-item>
<!--        <el-form-item
          label="定时发布"
          prop="issueTime"
          :label-width="formLabelWidth"
        >
          <el-date-picker v-model="newsForm.issueTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择发布时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item
          label="跳转链接"
          prop="jumpUrl"
          :label-width="formLabelWidth"
        >
          <el-input v-model="newsForm.jumpUrl"></el-input>
        </el-form-item>
        <el-form-item
          label="文章封面"
          prop="coverUrl"
          :label-width="formLabelWidth"
        >
          <div>
            <img v-if="newsForm.coverUrl" :src="newsForm.coverUrl" class="avatar" />
          </div>
          <div>
            <el-button type="primary" icon="el-icon-upload2" style="margin-top: 6px;" @click="handleShowImageForm(1)">选择图片</el-button>
          </div>
        </el-form-item>
        <el-form-item
          label="关联视频"
          prop="videoUrl"
          :label-width="formLabelWidth"
        >
        <div>
          <video v-if="newsForm.videoUrl" style="width: 160px; height: 90px" :src="newsForm.videoUrl" fit="contain"></video>
        </div>
        <div>
          <el-button type="primary" icon="el-icon-upload2" style="margin-top: 6px;" @click="handleShowVideoForm(1)">选择视频</el-button>
        </div>
        </el-form-item>
        <el-form-item label="文章正文" :label-width="formLabelWidth">
          <div class="article_content">
            <ShenMaEditor v-model="newsForm.bodyHtml" :message="newsForm.bodyHtml"></ShenMaEditor>
          </div>
        </el-form-item>

        <!-- 额外数据 -->
        <template v-for="(item,index) in typeVarList">
          <el-form-item v-if="item.varType=='String'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
            <el-input v-model="item.varValue" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="item.varType=='Integer'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
              <el-input v-model="item.varValue" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="item.varType=='DateTime'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
            <el-date-picker v-model="item.varValue" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item v-if="item.varType=='Text'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
            <el-input v-model="item.varValue" type="textarea" :rows="2" placeholder="请输入内容">
            </el-input>
          </el-form-item>
          <el-form-item v-if="item.varType=='Tags'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
            <el-select
                v-model="item.varValue"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择标签">
              </el-select>
          </el-form-item>
          <el-form-item v-if="item.varType=='Image'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
            <el-input v-model="item.varValue" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="item.varType=='Video'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
            <el-input v-model="item.varValue" autocomplete="off"></el-input>
          </el-form-item>
          <!-- 富文本 -->
          <el-form-item v-if="item.varType=='Html'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
            <ShenMaEditor v-model="item.varValue" :message="item.varValue"></ShenMaEditor>
          </el-form-item>

          <!-- 文档类型 -->
          <el-form-item v-if="item.varType=='File'" :key="index" :label="item.varBrief" :label-width="formLabelWidth">
           <el-input v-model="item.varValue" autocomplete="off" placeholder="从文档管理中复制文档地址到此输入框"></el-input>
          </el-form-item>
        </template>
      </el-form>
    </div>
    <div class="box">
      <el-button size="medium" type="primary" @click="submitNews">保存文章</el-button>
    </div>

    <!-- 选择图片 -->
    <el-dialog title="选择图片" :visible.sync="imgFormVisible">
      <div>
        <div>
          <!-- <vue-select-image :data-images="dataImages" :h="'100'" :w="'140'" :use-label="true" @onselectimage="onSelectImage"> -->
          <vue-select-image :data-images="dataImages" :h="'100'" :w="'100'" @onselectimage="onSelectImage">
          </vue-select-image>
        </div>
        <div>
          <el-pagination
            background
            layout="total, prev, pager, next"
            :current-page="pageNum"
            :page-size="pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            >
          </el-pagination>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="imgFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSelectImage">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 选择视频 -->
    <el-dialog title="选择视频" :visible.sync="videoFormVisible">
      <div>
        <div>
          <vue-select-image :data-images="dataVideos" :h="'90'" :w="'160'" @onselectimage="onSelectVideo">
          </vue-select-image>
        </div>
        <div>
          <el-pagination
            background
            layout="total, prev, pager, next"
            :current-page="pageNum"
            :page-size="pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            >
          </el-pagination>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="videoFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSelectVideo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {uploadServerURL} from '@/config'
import {
  addArticleArticle,
  setArticleArticle,
  getArticleById,
  updateNewsById,
  getArticleTypeById,
  getTypeVarList,
  getResourceList
} from '@/api/news.js'

import ShenMaEditor from '@/components/ShenMaEditor/index.vue'
import VueSelectImage from 'vue-select-image'
require('vue-select-image/dist/vue-select-image.css')

export default {
  name: 'NewsEdit',
  components: { VueSelectImage,ShenMaEditor },
  props: {
    typeId: { type: [String,Number], default: 0 },
    articleId: { type: [String,Number], default: 0 },
  },
  data() {
    return {
      uploadFileServer: uploadServerURL,
      user: null,
      typeInfo: {},
      typeVarList: [],
      newsForm: {
        articleId: null,
        title: null,
        authorId: null,
        authorName: null,
        editorId: null,
        editorName: null,
        keywords: null,
        description: null,
        brief: null,
        classicRank: 0,
        jumpUrl: null,
        coverUrl: null,
        videoUrl: null,
        rotateRank: 0,
        sortRank: 99999,
        topRank: 0,
        views: 0,
        issueTime: null,
        bodyHtml: '',
      },
      rules: {
        title: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
      },
      // 选择图片对话框
      imgFormVisible: false,
      formLabelWidth: '120px',
      dataImages: [],
      pageNum: 1,
      pageSize: 12,
      total: 0,
      imageSelectUrl: null,
      imageId: 0,
      videoFormVisible: false,
      dataVideos: [],
      videoId: 0,
      videoSelectUrl: null,
    }
  },
  created() {

  },

  mounted() {
    console.log('mounted...', this.typeId, this.articleId)
    let u = window.sessionStorage.getItem('user')
    if (u != null) {
      this.user = JSON.parse(u)
      console.log('created', this.user)
    } else {
      console.log('not login1')
        this.$store.dispatch('user/logout')
        const fullPath = this.$route.fullPath
        console.log('fullPath',fullPath);
        this.$router.push(`/login?redirect=${fullPath}`)
    }

    // 加载栏目信息
    this.loadTypeInfo()

    // 加载栏目扩展信息
    this.loadTypeVarList()

    // 加载图片、视频资源
    this.loadResourceImages()
    this.loadResourceVideos()


  },
  methods: {
    // 加载栏目信息
    loadTypeInfo() {
      let params = { id: this.typeId }
      getArticleTypeById(params).then((res) => {
        console.log('getArticleTypeById', res)
        this.typeInfo = res.data

        this.newsForm.typeName = this.typeInfo.typeName
        this.$forceUpdate()
      })
    },
    // 加载栏目扩展信息
    loadTypeVarList() {
      let params = { id: this.typeId }
      getTypeVarList(params).then(res => {
        console.log('getTypeVarList', res);
        this.typeVarList = res.data

        // 在表单生成后加载文章信息
        this.loadArticle(this.articleId)
      })
    },
    // 加载文章信息
    loadArticle(articleId) {
      // 加载文章信息
      if (articleId > 0) {
        let param = { id: articleId }
        getArticleById(param).then((res) => {
          console.log('getArticleById', res)
          this.newsForm = {...res.data.articleIndex,...res.data.articleBody}
          this.newsForm.typeName = this.typeInfo.typeName
          console.log('getArticleById', this.newsForm.bodyHtml);

          // this.$nextTick(() => {
          //   console.log('$nextTick', this.newsForm.bodyHtml);
          //   this.newsForm.bodyHtml = "hello"
          // })

          // 恢复扩展变量
          let extendVar = JSON.parse(res.data.articleIndex.extendVar)
          console.log('extendVar',extendVar)
          if(extendVar) {
            this.typeVarList.forEach(item => {
              let exist = extendVar.find(it => {
                console.log("==",it.varId,item.varId);
                  return it.varId == item.varId;
              });
              console.log('===',exist);
              if(exist == null) {
                extendVar.push(item)
              }
              else {
                exist.varType = item.varType
              }
            })
            this.typeVarList = extendVar
          }
          console.log('getArticleById', this.newsForm)
        })
      }
      else {
        this.newsForm.typeName = this.typeInfo.typeName
        this.newsForm.articleType = this.typeId
        this.newsForm.editorName = this.user.nickName
        this.newsForm.editorId = this.user.userId
        this.newsForm.authorName = this.user.nickName
      }
    },
    submitNews() {
      // this.newsForm.bodyHtml = this.newsForm.bodyHtml + 'A'
      // console.log('submitNews', this.newsForm.bodyHtml)
      // return
      // 检查必填项
      if (this.newsForm.title == '' || this.newsForm.title == null) {
        this.$message.error('没有填写文章标题')
        return
      }
      // 提交数据
      if(this.articleId > 0) {
        this.newsForm.articleId = this.articleId
        this.doSetArticle()
      }
      else {
        this.doAddArticle()
      }
    },
    handleAvatarSuccess(res, file) {
      console.log('handleAvatarSuccess', res)
      this.newsForm.coverUrl = res.data.url
    },
    handleVideoSuccess(res, file) {
      console.log('handleVideoSuccess', res)
      this.newsForm.videoUrl = res.data.url
    },
    doAddArticle() {
      let articleIndex = {}
      let articleBody = {}

      // 构造索引信息
      articleIndex.title = this.newsForm.title
      articleIndex.articleType = this.typeId
      articleIndex.authorId = this.user.userId
      articleIndex.authorName = this.newsForm.authorName
      articleIndex.editorId = this.user.userId
      articleIndex.editorName = this.newsForm.editorName
      articleIndex.keywords = this.newsForm.keywords
      articleIndex.description = this.newsForm.description
      articleIndex.brief = this.newsForm.brief
      articleIndex.classicRank = this.newsForm.classicRank
      articleIndex.jumpUrl = this.newsForm.jumpUrl
      articleIndex.coverUrl = this.newsForm.coverUrl
      articleIndex.videoUrl = this.newsForm.videoUrl
      articleIndex.rotateRank = this.newsForm.rotateRank
      articleIndex.sortRank = this.newsForm.sortRank
      articleIndex.views = this.newsForm.views
      articleIndex.topRank = this.newsForm.topRank

      // 构造新闻内容
      articleBody.bodyHtml = this.newsForm.bodyHtml
      // console.log(articleBody.bodyHtml);

      // 处理扩展变量
      console.log(this.typeVarList);
      articleIndex.extendVar = JSON.stringify(this.typeVarList)

      // 发送请求
      let param = {articleIndex,articleBody}
      addArticleArticle(param).then(res => {
        if(res.code == 200) {
          this.$message.success('添加文章成功')
          this.$store.dispatch('tabsBar/delVisitedRoute', this.$route)
          this.$router.push('/news/list/' + this.typeId)
        }
        else {
          this.$message.error(res.msg)
        }
      })
    },
    doSetArticle() {
      let articleIndex = {}
      let articleBody = {}

      console.log('user', this.user);

      // 构造索引信息
      articleIndex.articleId = this.articleId
      articleIndex.title = this.newsForm.title
      articleIndex.articleType = this.typeId
      articleIndex.authorId = this.user.userId
      articleIndex.authorName = this.newsForm.authorName
      articleIndex.editorId = this.user.userId
      articleIndex.editorName = this.newsForm.editorName
      articleIndex.keywords = this.newsForm.keywords
      articleIndex.description = this.newsForm.description
      articleIndex.brief = this.newsForm.brief
      articleIndex.classicRank = this.newsForm.classicRank
      articleIndex.jumpUrl = this.newsForm.jumpUrl
      articleIndex.coverUrl = this.newsForm.coverUrl
      articleIndex.videoUrl = this.newsForm.videoUrl
      articleIndex.rotateRank = this.newsForm.rotateRank
      articleIndex.sortRank = this.newsForm.sortRank
      articleIndex.views = this.newsForm.views
      articleIndex.topRank = this.newsForm.topRank

      // 构造新闻内容
      articleBody.articleId = this.articleId
      articleBody.bodyHtml = this.newsForm.bodyHtml
      console.log('set',this.newsForm.bodyHtml);

      // 处理扩展变量
      console.log(this.typeVarList);
      articleIndex.extendVar = JSON.stringify(this.typeVarList)

      // 发送请求
      let param = {articleIndex,articleBody}
      setArticleArticle(param).then(res => {
        if(res.code == 200) {
          this.$message.success('修改文章成功')
          this.$store.dispatch('tabsBar/delVisitedRoute', this.$route)
          this.$router.push('/news/list/' + this.typeId)
        }
        else {
          this.$message.error(res.msg)
        }
      })
    },
    handleUploadFileSuccess(item,res,file) {
      console.log(item, res, file)
      item.varValue = []
      item.varValue.push(res.data)
    },
    handleShowImageForm(id) {
      this.imageId = id
      this.loadResourceImages()
      this.imgFormVisible = true
    },
    handleShowVideoForm(id) {
      this.videoId = id
      this.loadResourceVideos()
      this.videoFormVisible = true
    },
    onSelectImage(image) {
      console.log(image)
      this.imageSelectUrl = image.src
    },
    onSelectVideo(video) {
      console.log(video)
      this.videoSelectUrl = video.src
    },
    submitSelectImage() {
      this.imgFormVisible = false
      if(this.imageId == 1) {
        this.newsForm.coverUrl = this.imageSelectUrl
      }
    },
    submitSelectVideo() {
      this.videoFormVisible = false
      if(this.videoId == 1) {
        let url = this.videoSelectUrl
        let videoUrl = url.substring(0, url.indexOf('?'));
        console.log('videoUrl='+videoUrl);
        this.newsForm.videoUrl = videoUrl
      }
    },
    loadResourceImages() {
      let param = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        keyWord: 'image'
      }
      getResourceList(param).then(res => {
        console.log('getResourceList', res);
        if(res.code == 200) {
          this.dataImages = []
          res.data.records.forEach(item => {
            let img = {
              id: item.fileId,
              src: item.fileUrl,
              alt: item.fileName
            }
            this.dataImages.push(img)
          })
          // this.tableData = res.data.records
          this.pageNum = res.data.current
          this.pageSize = res.data.size
          this.total = res.data.total
        }
      })
    },
    loadResourceVideos() {
      let param = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        keyWord: 'video'
      }
      getResourceList(param).then(res => {
        console.log('getResourceList', res);
        if(res.code == 200) {
          this.dataVideos = []
          res.data.records.forEach(item => {
            let img = {
              id: item.fileId,
              src: item.fileUrl + '?x-oss-process=video/snapshot,t_10000,m_fast',
              alt: item.fileName
            }
            this.dataVideos.push(img)
          })
          this.pageNum = res.data.current
          this.pageSize = res.data.size
          this.total = res.data.total
        }
      })
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageNum = val
      if(this.imgFormVisible) {
        this.loadResourceImages()
      }
      else {
        this.loadResourceVideos()
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      if(this.imgFormVisible) {
        this.loadResourceImages()
      }
      else {
        this.loadResourceVideos()
      }
    },
  },
}
</script>

<style>
.box {
  margin: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 90px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 160px;
  height: 90px;
  display: block;
}

/* .vue-select-image {
} */

/* .vue-select-image__item {
  margin-left: 4px;
}

.vue-select-image__thumbnail {
  border: 0px solid #ddd;
}

.vue-select-image__img {
  border: 1px solid #ddd;
  width: 140px;
  height: auto;
}

.vue-select-image__lbl {
  text-align: center;
} */
</style>
